<template>
    <MapView v-if="defectList.length > 0" :defects="defectList"></MapView>
</template>

<script lang="ts" setup>
import {
    ref,
    reactive,
    onMounted,
    onUnmounted,
} from 'vue'

import useDraw from '@/utils/useDraw'

import { formatTime } from '@/utils/index'
import { WEEK } from '@/constant/index'
import { title, subtitle } from '@/constant/index'


import LbmLeftPads from '../lbm-left/index-pads.vue'
import LbmLeftPie from '../lbm-left/index-pie.vue'
import LbmLeftBottom from '../lbm-left-bottom/index.vue'
import LbmRight from '../lbm-right/index.vue'
import LbmRightTerms from '../lbm-right/terms.vue'

import MapView from '../map/MapView.vue'



// * 加载标识
const loading = ref<boolean>(true)

const defectList = ref<any[]>([])

const totalInfo = ref<any | undefined>(undefined)



const categoryList = ref<any[]>([])
const routeList = ref<any[]>([])

// * 时间内容
const timeInfo = reactive({
    setInterval: 0,
    dateDay: '',
    dateYear: '',
    dateWeek: ''
})
// * 适配处理
const { appRef, calcRate, windowDraw, unWindowDraw } = useDraw()
// 生命周期
onMounted(() => {
    loadData()
    handleTime()
    // todo 屏幕适应
    windowDraw()
    calcRate()
})

onUnmounted(() => {
    unWindowDraw()
    clearInterval(timeInfo.setInterval)
})

const formatDate = (dateString) => {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    return `${year}-${month}-${day}`;
}

const parseCoordinates = (str) => {
    //"靳桃线（靳店-南桃湾）1.MP4_36.4953642_110.979484_1114.715_847.jpg"
    const regex = /_(\d+\.\d+)_(\d+\.\d+)_/;
    const match = str.match(regex);
    if (match) {
        const lat = Number(match[1]);
        const lng = Number(match[2]);
        return [lng, lat];
    } else {
        return null;
    }
}

const loadTotalData = async () => {
    const cacheKey = 'totalDataCache'
    const cacheData = localStorage.getItem(cacheKey)
    var totalJSONData;
    if (cacheData) {
        // 如果缓存存在，则从缓存中读取数据
        totalJSONData = JSON.parse(cacheData)
        totalInfo.value = totalJSONData
    } else {
        // 如果缓存不存在，则从服务器获取数据
        const response = await fetch("http://220.194.128.226:39005/statsDefects");
        totalJSONData = await response.json();
        console.log("totalJSONData = ", totalJSONData)
        // 将获取到的数据存储到缓存中，并设置过期时间为24小时
        localStorage.setItem(cacheKey, JSON.stringify(totalJSONData))
        localStorage.setItem(`${cacheKey}:expire`, (Date.now() + 24 * 60 * 60 * 1000).toString())
        totalInfo.value = totalJSONData
    }

    let _categoryList = [];
    console.log(`totalJSONData.event_type_stats=`, totalJSONData.event_type_stats);
    for (const eventType in totalJSONData.event_type_stats) {

        const count = totalJSONData.event_type_stats[eventType];
        console.log(`${eventType}: ${count}`);
        console.log(`${eventType}: ${count}`);
        _categoryList.push({
            value: count,
            name: eventType
        })
    }
    categoryList.value = _categoryList;

    let _routeList = [];
    for (const eventType in totalJSONData.routeStats) {
        const count = totalJSONData.routeStats[eventType];
        console.log(`${eventType}: ${count}`);
        console.log(`${eventType}: ${count}`);
        if (!eventType) {
            continue;
        }
        _routeList.push({
            value: count,
            name: eventType
        })
    }
    routeList.value = _routeList;

}
const loadListData = async () => {
    //http://220.194.128.226:39005/infodc/defectGet?beginDate=2023-05-02&endDate=2023-05-03&pageNo=20&pageSize=30

    const response = await fetch("http://220.194.128.226:39005/infodc/defectGet?beginDate=2023-05-02&endDate=2023-05-03&pageNo=1&pageSize=300");
    const defectsJSONData = await response.json();
    console.log('defectsJSONData', defectsJSONData)
    let data = [];
    defectsJSONData.records.map((defect) => {
        // image.defects.map((defect) => {
        //   data.push([defect.defect_type, defect.route, formatDate(defect.snap_date), parseCoordinates(image.image_id)])
        // })
        data.push([defect.defect_type, defect.route, formatDate(defect.snap_date), [defect.longitude, defect.latitude]])
    })

    console.log('defectList.value', JSON.stringify(data))
    defectList.value = data


}

// methods
// todo 处理 loading 展示
const loadData = async () => {

    await loadListData();
    await loadTotalData();

    setTimeout(() => {
        loading.value = false
    }, 500)
}

// todo 处理时间监听
const handleTime = () => {
    timeInfo.setInterval = setInterval(() => {
        const date = new Date()
        timeInfo.dateDay = formatTime(date, 'HH: mm: ss')
        timeInfo.dateYear = formatTime(date, 'yyyy-MM-dd')
        timeInfo.dateWeek = WEEK[date.getDay()]
    }, 1000)
}

</script>

<style lang="scss" scoped>
@import '@/assets/scss/index.scss';
</style>
